import React, {PureComponent,Component} from 'react'
import {
    View,
    SectionList,
    ScrollView,
    Text,
    Image,
    TouchableOpacity,
    Dimensions,
    StyleSheet,
    Animated,
    SafeAreaView,
    ToastAndroid, DeviceEventEmitter,

} from 'react-native'

import color from '../../widget/color'
import OrderInfoView from '../../widget/detail/OrderInfoView'
import OrderAddressView from '../../widget/detail/OrderAddressView'
import OrderJieSuanView from '../../widget/detail/OrderJieSuanView'
import OrderPayView from '../../widget/detail/OrderPayView'
import method  from '../../api/method'
import api  from '../../api/api'
import {fetchGetRequest,fetchPostRequest}  from '../../api/NetworkTool'
// import Alipay from "react-native-yunpeng-alipay";
// import * as WeChat from "react-native-wechat";
import Tips from 'react-native-root-tips'
import {NavigationActions} from "react-navigation";
import XPay from 'react-native-puti-pay'

import CommonAlertDialog from '../../widget/dialog/CommonAlertDialog'
import BuySuccessScene from './BuySuccessScene'
import NetTool from "../../api/NetTool";
const {width} = Dimensions.get('window')

type Props = {
    navigation:any,
}

export default class CourseOrderScene extends PureComponent<Props>{
    static navigationOptions = ({navigation}) => ({
        headerTintColor:'#333333',
        headerStyle:{backgroundColor:'white'},
        title:'订单',
        headerRight:<Text/>,
        headerLeft:<TouchableOpacity onPress={()=>{
            // navigation.state.params.uploadData
            DeviceEventEmitter.emit('orderBack')
        }}>
            <Image style={{marginLeft:12}} source={require('../../../res/img/gobal_back.png')}/>
        </TouchableOpacity>
    });

    constructor(props){
        super(props)
        this.state = {
            payment:'wxpay',
            address:{},
            coupon:null,
            time:60,
            coupon_info:null,
            payShow:false,
            orderSn:null,
            show_alert:false,
        }
        XPay.setAlipayScheme('alipayDemo')
        XPay.setWxId('wx8ad5c98436e7aefa')
    }


    componentDidMount() {
        const {course,address,order} = this.props.navigation.state.params
        let obj = '[('+course.id+',0'+')]'
        this.setState({address:address,coupon:obj})
        DeviceEventEmitter.addListener('orderBack', () => {
            this.setState({payShow: true,})
        });

    }
    pay(){
        if (this.state.orderSn){
            fetchGetRequest(api.queryPay, method.get, {orderSn:this.state.orderSn})
                .then(res=>{
                    if (res.status == 'unpaid'){
                        this.setState({show_alert:true})
                    }
                })
                .catch(err=>{
                    Tips.showInfo(err,{mask:true})
                })
            return
        }
        const {course,address,order} = this.props.navigation.state.params

        let params = {
                productId:course.id,
                payment:this.state.payment,
                clientType:'app',
                addressId:this.state.address.id,
                coupon:this.state.coupon
            }
        fetchGetRequest(api.sponsorPay,method.get,params)
            .then(res=>{
                console.log(res.payParam)
                this.setState({orderSn:res.orderSn})
                this.sponsorPay(res.payParam)

            })
            .catch(err=>{
                Tips.showInfo(err,{mask:true})
            })
    }
    sponsorPay(params) {
        if(this.state.payment == 'alipay'){
            XPay.alipay(params,(res)=>{
                if (res.resultStatus == '9000') {
                    Tips.showSuccess('购买成功',{mask:true})
                    this.props.navigation.navigate('BuySuccessScene')
                }else if(res.resultStatus == '8000'){
                    Tips.showInfo('购买确认中...',{mask:true})
                }else {
                    Tips.showFail('购买失败',{mask:true})
                }
            })

        }else if(this.state.payment == 'wxpay'){
            let wechat_params = {
                partnerId:params.partnerid,
                prepayId: params.prepayid,
                packageValue:params.package,
                nonceStr: params.noncestr,
                timeStamp: params.timestamp,
                sign: params.sign,
            }
            XPay.wxPay(wechat_params,(res)=>{
                console.log('res wchat',res)
                if(res.errCode == 0){
                    Tips.showSuccess('购买成功',{mask:true})
                    this.props.navigation.navigate('BuySuccessScene')
                }else {
                    Tips.showFail('购买失败',{mask:true})
                }
            })
        }


    }
    addressRequestData = async() =>{

        let json = await NetTool.fetchGetRequest(api.getUserAddr,method.get)
        
        if (json.addrList.length > 0){
            let address = json.addrList[0]

            this.setState({address:address})
        }else {
            this.setState({address:{}})
        }

    }

    render(){
        const {course,address,order} = this.props.navigation.state.params

        let courseId = parseInt(course.id)

        return (
            <SafeAreaView style={{flex:1,backgroundColor:"#f5f5f5",}}>

                <ScrollView>
                    <View style={{backgroundColor:'white',shadowColor:'#3C3C3C', shadowOffset:{h:2,w:2},
                        shadowRadius:1,marginLeft:-2, flex:
                            1,shadowOpacity:0.4, borderRadius:3,paddingBottom:10}}>
                        <OrderInfoView course={course} callBack={(info)=>{
                            // let obj = {
                            //     [courseId]:info.id,
                            // }
                            console.log('info',info)
                            let obj = '[('+courseId+','+info.id+')]'
                            this.setState({coupon:obj,coupon_info:info})
                        }} cancelPress={()=>{
                            let obj = '[('+courseId+',0'+')]'
                            this.setState({coupon:obj})
                        }}/>
                        <OrderAddressView onPress={()=>{
                            fetchGetRequest(api.getUserAddr, method.get)
                                .then(res=>{
                                    if (res.addrList.length > 0) {
                                        this.props.navigation.navigate('MineAddressScene',{isOrder:true,callback:(data)=>{
                                                this.addressRequestData()
                                            }})
                                    }else {
                                        this.props.navigation.navigate('AddAddressScene',{isOrder:true,callback:(data)=>{
                                                this.addressRequestData()
                                            }})
                                    }
                                })
                                .catch(err=>{})

                        }} address={this.state.address} navigation={this.props.navigation} style={{marginTop:15}}/>
                        <OrderJieSuanView coupon={this.state.coupon_info}  course={course} style={{marginTop:15}} />
                        <OrderPayView course={course} style={{marginTop:15}} callback={(payParms)=>{
                            this.setState({payment:payParms})
                        }}/>
                    </View>
                </ScrollView>
                <CommonAlertDialog show={this.state.payShow} title={'确定放弃支付吗？'} onPress={()=>{
                    this.props.navigation.goBack()
                }} closeModal={(st)=>{
                    this.setState({payShow:st})
                }} confirmTitle={'确定'}/>
                <CommonAlertDialog show={this.state.show_alert} title={'该课程已生成订单！'} onPress={()=>{
                    this.props.navigation.navigate('MineOrderScene',{number:1})
                }} closeModal={(st)=>{
                    this.setState({show_alert:st})
                }} confirmTitle={'去支付'}/>
                <TouchableOpacity style={{height:50,backgroundColor:color.globalMainColor,alignItems:'center',justifyContent:"center"}}
                                  onPress={()=>{
                                      if (!this.state.address.id){
                                          Tips.showWarn('请选择地址',{mask:true})
                                          return
                                      }else {
                                          this.pay()
                                      }
                                  }}>
                    <Text style={{fontSize:16,fontWeight:'bold',color:'white'}}>支付</Text>
                </TouchableOpacity>
            </SafeAreaView>
        )
    }
}